// pkgTask/pages/prebid-communication/index.js
const app = getApp();
const util = require('../../../utils/util.js');
const lbbService = require('../../../pages/service/service.js');
const lbbTaskService = require('../service/task-service.js');
const operateMethod =require('../service/operatef.js');
Page({
    /**
     * 页面的初始数据
     */
    data: {
        interactOption: [{
                text: '请选择',
                value: -1
            },
            {
                text: '已沟通',
                value: 1
            }, {
                text: '未沟通',
                value: 0
            }
        ],
        condition: '',
        isArriveScene: 1,
        interactList: [{}],
        columnsItemThings: [{
            text: '医院轮椅投放',
            value: 1
        }, {
            text: '盲投',
            value: 2
        }],
        showInteractPerson: false,
        userList: [{
            label: '小李',
            value: '1'
        }, {
            label: '小长',
            value: '2'
        }],
        reasonList: [{
                text: '请选择',
                value: ''
            },
            {
                text: '原因一',
                value: 1
            }
        ],
        reason: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.setData({
            operationType: options.type,
            taskType:options.taskType,
            taskId: options.taskId,
            hospitalId: options.hospitalId,
            operationlist : options.operationlist?JSON.parse(options.operationlist):[],
            operationTypeCode:options.operationTypeCode,
            activeKey:options.activeKey
        })
        if (options.type == 'agent_communication') {
            wx.setNavigationBarTitle({
                title: '代理商沟通'
            })
        }else if(options.type == 'agent_urgent_communication'){
            wx.setNavigationBarTitle({
                title: '代理商紧急情况沟通'
            })
        } else if(options.type == 'handle_contract'){
            wx.setNavigationBarTitle({
                title: '合同处理'
            }) 
        }
        that.getDetailById()
        that.getAgentList()
        that.getProjectList('link_up')
        that.getProjectList(that.data.taskType=='long'?'notcommunicated_longtask':'causes_blindness')
        that.getProjectList(that.data.taskType=='long'?'longTask_communication':'communication_matters')
        that.getCommunicateFeedback()
    },
    //获取任务详情
    getDetailById() {
        let that = this
        let InterfaceItem=that.data.taskType=='long'?lbbTaskService.getLongDetailById:lbbTaskService.getDetailById
        InterfaceItem({
            taskId: that.data.taskId
        }, function (res) {
            if(res.data){
                that.setData({
                taskProjectText: res.data.taskProjectText,
                taskClassificationName: res.data.taskClassificationName,
                hospitalName: res.data.hospitalName,
                taskDesc: res.data.taskDesc,
                taskImages: res.data.taskImages ? res.data.taskImages.split(',') : [],
                isUrgent: res.data.isUrgent
            })
            }  
        })
    },
    //获取数据字典值
    getProjectList(code) {
        let that = this
        lbbTaskService.getDictByCode({
            code: code
        }, function (res) {
            console.log(res)
            if (code == 'communication_matters'||code=='longTask_communication') {
                that.setData({
                    columnsItemThings: res.data
                })
            } else if (code == 'link_up') {
                res.data.unshift({
                    text: '请选择',
                    value: ''
                })
                that.setData({
                    interactOption: res.data
                })
            } else if (code == 'causes_blindness'||code=='notcommunicated_longtask') {
                res.data.unshift({
                    text: '请选择',
                    value: ''
                })
                that.setData({
                    reasonList: res.data
                })
            }
        })
    },
    //获取代理列表
    getAgentList(){
        let that =this
        lbbTaskService.getAgentList({mechanismId:that.data.hospitalId},function(res) {
            that.setData({
                userList:res.data
            })
        })
    },
    //回显
    getCommunicateFeedback() {
        let that = this
        lbbTaskService.getCommunicateFeedback({
            taskId: that.data.taskId,
            operationType: that.data.operationType
        }, function (res) {
            if (res.data) {
                if (res.data.conditionList.length == 0 || !res.data.conditionList||res.data.condition==0) {
                    res.data.interactList = [{}]
                } else {
                    res.data.conditionList.forEach(item => {
                        item.images = item.images ? item.images.split(',') : ''
                        item.remark = item.remark ? item.remark : ''
                        item.username=that.data.userList.find(itm=>itm.value=item.userId).label
                    })
                    res.data.interactList = res.data.conditionList
                }
                res.data.remark = res.data.remark ? res.data.remark : ''
                res.data.images = res.data.images ? res.data.images.split(',') : ''
                that.setData({
                    ...res.data
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },
    //沟通情况选择回调
    onChangeInteract(e) {
        this.setData({
            condition: e.detail
        })
    },
    //是否到现场选择回调
    onChangeRadio(e) {
        this.setData({
            isArriveScene: e.detail
        })
    },
    //打开沟通人弹窗
    onBindInteractPerson(e) {
        this.setData({
            showInteractPerson: true,
            optionIndex: e.currentTarget.dataset.index
        })
    },
    //选择人回调
    onClickItem(e) {
        console.log(555, e)
        this.data.interactList[this.data.optionIndex].username = e.detail.name
        this.data.interactList[this.data.optionIndex].userId = e.detail.id
        this.setData({
            showInteractPerson: false,
            interactList: this.data.interactList
        })
    },
    //打开沟通事项
    onBindItemThings(e) {
        console.log(e)
        this.setData({
            showItemThings: true,
            optionIndex: e.currentTarget.dataset.index
        })
    },
    //沟通事项选择回调
    okSelect(e) {
        console.log(11, e)
        this.data.interactList[this.data.optionIndex].matterInfoText = e.detail.text
        this.data.interactList[this.data.optionIndex].matterInfo = e.detail.value
        this.setData({
            interactList: this.data.interactList
        })
    },
    //备注
    changeRemark(e) {
        this.setData({
            optionIndex: e.currentTarget.dataset.index
        })
        this.data.interactList[this.data.optionIndex].remark = e.detail.value
        this.setData({
            interactList: this.data.interactList
        })
    },
    //图片上传
    setImgArr(e) {
        let that = this
        let imgArray = e.detail;
        let newUpLoadImg = []
        let oldUpLoadImg = []
        imgArray.forEach(item => {
            if (item.indexOf('http://tmp/') != -1||item.indexOf('wxfile://tmp')!=-1) {
                newUpLoadImg.push(item)
            } else {
                oldUpLoadImg.push(item)
            }
        })
        wx.showLoading({
            title: '正在上传图片',
            mask: true
        })
        util.newUpLoadImg(app.globalData.header, newUpLoadImg, 0, [], function (imgIdArray) {
            console.log('item================>', imgIdArray)
            wx.hideLoading()
            oldUpLoadImg.push(...imgIdArray)
            that.data.interactList[e.currentTarget.dataset.index].images = oldUpLoadImg
        });
    },
    //删除
    delTask(e) {
        this.data.interactList.splice(e.currentTarget.dataset.index, 1)
        this.setData({
            interactList: this.data.interactList
        })
    },
    //添加
    addTask(e) {
        this.data.interactList.push({})
        this.setData({
            interactList: this.data.interactList
        })
    },
    //选择未沟通原因
    onChangeReason(e) {
        this.setData({
            reason: e.detail
        })
    },
    //未沟通备注
    changeRemarkNot(e) {
        this.setData({
            remark: e.detail.value
        })
    },
    //未沟通图片
    setImgArrNot(e) {
        let that = this
        let imgArray = e.detail;
        let newUpLoadImg = []
        let oldUpLoadImg = []
        imgArray.forEach(item => {
            if (item.indexOf('http://tmp/') != -1||item.indexOf('wxfile://tmp')!=-1) {
                newUpLoadImg.push(item)
            } else {
                oldUpLoadImg.push(item)
            }
        })
        wx.showLoading({
            title: '正在上传图片',
            mask: true
        })
        util.newUpLoadImg(app.globalData.header, newUpLoadImg, 0, [], function (imgIdArray) {
            console.log('item================>', imgIdArray)
            wx.hideLoading()
            oldUpLoadImg.push(...imgIdArray)
            that.data.images = oldUpLoadImg
        });
    },
    //提交
    btnSubmit() {
        let that = this
        let obj = {}
        if (that.data.condition == 0) {
            let checkList = []
            obj = {
                condition: that.data.condition,
                isArriveScene: that.data.isArriveScene,
                reason: that.data.reason,
                remark: that.data.remark ? that.data.remark : '',
                images: that.data.images ? that.data.images.toString() : '',
                operationType: that.data.operationType,
                taskId: that.data.taskId
            }
            if (obj.isArriveScene != 0 && obj.isArriveScene != 1) {
                checkList.push(0)
            } else {
                checkList.push(1)
            }
            if (!obj.reason && obj.reason !== 0) {
                checkList.push(0)
            } else {
                checkList.push(1)
            }
            if (checkList.indexOf(0) != -1) {
                that.openPrompt()
            } else {
                lbbTaskService.communicateFeedback({
                    feedbackInfo: JSON.stringify(obj)
                }, function (res) {
                    if (that.data.activeKey == 3) {
                        wx.navigateBack({
                            delta: 1
                        })
                    } else {
                        operateMethod(that.data.operationlist, that.data.taskId, that.data.hospitalId, that.data.taskType, that.data.operationTypeCode)
                    }
                })
            }
        } else if (that.data.condition == 1) {
            let checkList = []
            if(that.data.operationType!='handle_contract'){
                that.data.interactList.forEach(item => {
                item.images = item.images ? item.images.toString() : '',
                    item.remark = item.remark ? item.remark : ''
                if (!item.userId) {
                    checkList.push(0)
                } else {
                    checkList.push(1)
                }
                if (!item.matterInfo && item.matterInfo != 0) {
                    checkList.push(0)
                } else {
                    checkList.push(1)
                }
            })  
            }else{
                that.setData({
                    conditionList:[]
                })
            }
            obj = {
                condition: that.data.condition,
                isArriveScene: that.data.isArriveScene,
                conditionList: that.data.interactList,
                operationType: that.data.operationType,
                taskId: that.data.taskId
            }
            if (obj.isArriveScene != 0 && obj.isArriveScene != 1) {
                checkList.push(0)
            } else {
                checkList.push(1)
            }
            if (checkList.indexOf(0) != -1) {
                that.openPrompt()
            } else {
                lbbTaskService.communicateFeedback({
                    feedbackInfo: JSON.stringify(obj)
                }, function (res) {
                    if (that.data.activeKey == 3) {
                        wx.navigateBack({
                            delta: 1
                        })
                    } else {
                        operateMethod(that.data.operationlist, that.data.taskId, that.data.hospitalId, that.data.taskType, that.data.operationTypeCode)
                    }
                })
            }
        } else {
            that.openPrompt()
        }
    },
    //校验提示
    openPrompt() {
        wx.showToast({
            title: '请检查必填项',
            icon: 'error',
            duration: 2000
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})